package com.moyun.zbmy.zizhou.ui.fragment;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.base.BaseFragment;
import com.moyun.zbmy.zizhou.beans.ChooseCityVo;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.HighRiseBean;
import com.moyun.zbmy.zizhou.beans.HighRiseImage;
import com.moyun.zbmy.zizhou.beans.HighRiseCharacterBean;
import com.moyun.zbmy.zizhou.beans.HighRiseNewsInfo;
import com.moyun.zbmy.zizhou.beans.HighRiseTypeBean;
import com.moyun.zbmy.zizhou.beans.HighRiseUser;
import com.moyun.zbmy.zizhou.beans.HighRiseVo;
import com.moyun.zbmy.zizhou.beans.Image;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.HighRiseAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.HighRiseNewsListAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.GlideUtil;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 政声
 */
public class HighRiseFragment extends ColumnBaseFragment {

    @BindView(R.id.high_rise_top_img)
    protected ImageView topImg;
    @BindView(R.id.tab_layout_1)
    protected RelativeLayout tabLayout_1;
    @BindView(R.id.tab_layout_2)
    protected RelativeLayout tabLayout_2;
    @BindView(R.id.tab_layout_3)
    protected RelativeLayout tabLayout_3;
    @BindView(R.id.tab_layout_4)
    protected RelativeLayout tabLayout_4;
    @BindView(R.id.tab_1)
    protected CustomFontTextView tab_1;
    @BindView(R.id.tab_2)
    protected CustomFontTextView tab_2;
    @BindView(R.id.tab_3)
    protected CustomFontTextView tab_3;
    @BindView(R.id.tab_4)
    protected CustomFontTextView tab_4;
    @BindView(R.id.tab_line_1)
    protected View tabLine_1;
    @BindView(R.id.tab_line_2)
    protected View tabLine_2;
    @BindView(R.id.tab_line_3)
    protected View tabLine_3;
    @BindView(R.id.tab_line_4)
    protected View tabLine_4;

    private int currentTabIndex = -1;
    private int userSize = 0;
    private HighRiseSubFragment currentFragment;
    private List<IListShowData> list;
    private List<IListShowData> listG = new ArrayList<>();//天天学习
    private List<IListShowData> listP = new ArrayList<>();//天府新语
    private List<IListShowData> listC = new ArrayList<>();//绵州政声
    private List<IListShowData> listA = new ArrayList<>();//三台强音
    private boolean isRefresh = false;

    public HighRiseFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_high_rise, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        getChannels();
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

    }


    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        isRefresh = true;
        getChannels();
        JLog.e("--------------HighRiseFragment-----refreshData--------------");
    }

    /**
     * 请求基础的路径数据
     */
    private void getChannels() {
        NetUtils.getNetAdapter().getHighRiseList(getOwnerName(), channelUrl, new AbsNetCallBack<HighRiseBean>(HighRiseBean.class) {

            @Override
            public void onSuc(HighRiseBean vo) {
                if (null != vo) {
                    initData(vo);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });
    }

    /**
     * 初始化 高层数据
     *
     * @param data
     */
    private void initData(HighRiseBean data) {
        if (!TextUtils.isEmpty(data.getImage())) {
            GlideUtil.getGlid(getContext(), data.getImage()).centerCrop().error(R.mipmap.high_top_default).into(topImg);
        }
        list = new ArrayList<>();
        if (null != data.getUserList()) {
            HighRiseCharacterBean cBean;
            userSize = data.getUserList().size();
            for (int i = 0; i < data.getUserList().size(); i++) {
                HighRiseUser user = data.getUserList().get(i);
                cBean = new HighRiseCharacterBean();
                cBean.setType(user.getType());
                cBean.setViewType(HighRiseAdapter.HIGH_RISE_CHARACTER);
                cBean.setIcon(user.getPicture());
                cBean.setId(user.getUserId());
                cBean.setName(user.getUserName());
                cBean.setPost(user.getPosition());
                cBean.setIntroJson(user.getPersonInfo());
                cBean.setTempSpecialJson(user.getSpecialInfo());
                List<NewsItem> l = user.getNewsList();
                if (null != l) {
                    List<HighRiseNewsInfo> newsList = new ArrayList<>();
                    HighRiseNewsInfo info;
                    for (int k = 0; k < l.size(); k++) {
                        info = new HighRiseNewsInfo(HighRiseNewsListAdapter.NEWS_TYPE, "", l.get(k));
                        newsList.add(info);
                    }
                    if(l.size()>0&&!TextUtils.isEmpty(user.getMoreNewsUrl())) {
                        info = new HighRiseNewsInfo(HighRiseNewsListAdapter.LOAD_MORE_TYPE, "查看更多", null);
                        info.setMoreUrl(user.getMoreNewsUrl());
                        newsList.add(info);
                    }
                    cBean.setNewsList(newsList);
                }
                list.add(cBean);
            }
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) instanceof HighRiseCharacterBean) {
                    HighRiseCharacterBean b = (HighRiseCharacterBean) list.get(i);
                    getSpecialList(b.getTempSpecialJson(), i);
                }
            }

        }


    }

    /**
     * 获取高层人员的新闻子专题类型
     *
     * @param url
     * @param position
     */
    private void getSpecialList(String url, final int position) {
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(NewsItem.class) {
            @Override
            public void onSuc(List<NewsItem> datas) {
                ArrayList<NewsItem> subSpecialList = getPageResponse().getData().getSubSpecialList();
                if (ListUtils.isListValued(subSpecialList)) {
                    List<HighRiseTypeBean> typeList = new ArrayList<>();
                    HighRiseTypeBean typeBean;
                    for (NewsItem item : subSpecialList) {
                        typeBean = new HighRiseTypeBean();
                        typeBean.setType(item.getNewsId());
                        typeBean.setTypeName(item.getNewsTitle());
                        typeBean.setTypeUrl(item.getNewsUrl());
                        typeList.add(typeBean);
                    }
                    if (list.get(position) instanceof HighRiseCharacterBean && typeList.size() > 0) {
                        HighRiseCharacterBean b = (HighRiseCharacterBean) list.get(position);
                        b.setNewsTypeList(typeList);
                    }
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
            }

            @Override
            public void onEnd() {
                userSize--;
                if (userSize == 0) {
                    handleData();
                    if (!isRefresh) {
                        onTabChanged(0);
                    } else {
                        onTabChanged(currentTabIndex);
                    }
                }
            }
        });
    }

    private void handleData() {
        if (ListUtils.isListValued(list)) {
            listG.clear();
            listP.clear();
            listC.clear();
            listA.clear();
            for (int i = 0; i < list.size(); i++) {
                IListShowData item = list.get(i);
                if (item instanceof HighRiseCharacterBean) {
                    HighRiseCharacterBean bean = (HighRiseCharacterBean) item;
                    if ("1".equalsIgnoreCase(bean.getType())) {
                        listG.add(bean);
                    } else if ("2".equalsIgnoreCase(bean.getType())) {
                        listP.add(bean);
                    } else if ("3".equalsIgnoreCase(bean.getType())) {
                        listC.add(bean);
                    } else {
                        listA.add(bean);
                    }
                }
            }
        }
    }

    @OnClick(value = {R.id.tab_layout_1, R.id.tab_layout_2, R.id.tab_layout_3, R.id.tab_layout_4})
    public void tabClick(View view) {
        switch (view.getId()) {
            case R.id.tab_layout_1:
                onTabChanged(0);
                break;
            case R.id.tab_layout_2:
                onTabChanged(1);
                break;
            case R.id.tab_layout_3:
                onTabChanged(2);
                break;
            case R.id.tab_layout_4:
                onTabChanged(3);
                break;
        }
    }

    public void onTabChanged(int index) {
        if (currentTabIndex != index) {
            tab_1.setTextColor(getResources().getColor(R.color.colorGray4D4D4D));
            tabLine_1.setVisibility(View.GONE);
            tab_2.setTextColor(getResources().getColor(R.color.colorGray4D4D4D));
            tabLine_2.setVisibility(View.GONE);
            tab_3.setTextColor(getResources().getColor(R.color.colorGray4D4D4D));
            tabLine_3.setVisibility(View.GONE);
            tab_4.setTextColor(getResources().getColor(R.color.colorGray4D4D4D));
            tabLine_4.setVisibility(View.GONE);

            switch (index) {
                case 0: //天天学习
                    addFragment("HighRiseSubFragment1");
                    currentTabIndex = index;
                    tab_1.setTextColor(getResources().getColor(R.color.colorTxBlackMain));
                    tabLine_1.setVisibility(View.VISIBLE);
                    break;
                case 1:  //天府新语
                    addFragment("HighRiseSubFragment2");
                    currentTabIndex = index;
                    tab_2.setTextColor(getResources().getColor(R.color.colorTxBlackMain));
                    tabLine_2.setVisibility(View.VISIBLE);
                    break;
                case 2:   //绵州政声
                    addFragment("HighRiseSubFragment3");
                    currentTabIndex = index;
                    tab_3.setTextColor(getResources().getColor(R.color.colorTxBlackMain));
                    tabLine_3.setVisibility(View.VISIBLE);
                    break;
                case 3:   //三台强音
                    addFragment("HighRiseSubFragment4");
                    currentTabIndex = index;
                    tab_4.setTextColor(getResources().getColor(R.color.colorTxBlackMain));
                    tabLine_4.setVisibility(View.VISIBLE);
                    break;

            }
        } else {
            if (currentTabIndex == 0) {
                currentFragment.updateList(listG);
            } else if (currentTabIndex == 1) {
                currentFragment.updateList(listP);
            } else if (currentTabIndex == 2) {
                currentFragment.updateList(listC);
            } else if (currentTabIndex == 3) {
                currentFragment.updateList(listA);
            }
        }
    }

    private void addFragment(String fTag) {
        //判断这个标签是否存在Fragment对象,如果存在则返回，不存在返回null
        HighRiseSubFragment fragment = (HighRiseSubFragment) getChildFragmentManager().findFragmentByTag(fTag);
        //初始化Fragment事物
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        // 如果这个fragment不存于栈中
        if (fragment == null) {
            //根据RaioButton点击的Button传入的tag，实例化，添加显示不同的Fragment
            if (fTag.equals("HighRiseSubFragment1")) {
                fragment = new HighRiseSubFragment();
                fragment.setList(listG);
            } else if (fTag.equals("HighRiseSubFragment2")) {
                fragment = new HighRiseSubFragment();
                fragment.setList(listP);
            } else if (fTag.equals("HighRiseSubFragment3")) {
                fragment = new HighRiseSubFragment();
                fragment.setList(listC);
            } else if (fTag.equals("HighRiseSubFragment4")) {
                fragment = new HighRiseSubFragment();
                fragment.setList(listA);
            }
            //在添加之前先将上一个Fragment隐藏掉
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(R.id.container, fragment, fTag);
            transaction.commitAllowingStateLoss();
            //更新可见
            currentFragment = fragment;
        } else {
            //如果添加的Fragment已经存在，则将隐藏掉的Fragment再次显示,其余当前
            transaction.show(fragment);
            transaction.hide(currentFragment);
            if (fTag.equals("HighRiseSubFragment1")) {
                fragment.updateList(listG);
            } else if (fTag.equals("HighRiseSubFragment2")) {
                fragment.updateList(listP);
            } else if (fTag.equals("HighRiseSubFragment3")) {
                fragment.updateList(listC);
            } else if (fTag.equals("HighRiseSubFragment4")) {
                fragment.updateList(listA);
            }
            //更新可见
            currentFragment = fragment;
            transaction.commitAllowingStateLoss();
        }
    }

}
